package com.csun.cmny.provider.controller;

import com.csun.cmny.core.annotation.LogAnnotation;
import com.csun.cmny.core.annotation.ValidateAnnotation;
import com.csun.cmny.core.support.BaseController;
import com.csun.cmny.provider.dto.PlanDto;
import com.csun.cmny.provider.dto.PlanQueryDto;
import com.csun.cmny.provider.model.domain.OmcPlan;
import com.csun.cmny.provider.model.domain.OmcPlanNew;
import com.csun.cmny.provider.model.domain.OmcShifts;
import com.csun.cmny.provider.resolver.CmnyMessageSource;
import com.csun.cmny.provider.service.OmcPlanNewService;
import com.csun.cmny.provider.service.OmcPlanService;
import com.csun.cmny.provider.service.OmcShiftsService;
import com.csun.cmny.provider.validator.OmcPlanAddValidator;
import com.csun.cmny.provider.validator.OmcPlanEditValidator;
import com.csun.cmny.util.wrapper.WrapMapper;
import com.csun.cmny.util.wrapper.Wrapper;
import com.github.pagehelper.PageInfo;
import com.google.common.base.Preconditions;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.regex.Pattern;

@RestController
@RequestMapping(value = "/plan", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class OmcPlanController extends BaseController {

    @Resource
    private CmnyMessageSource cmnyMessageSource;

    @Resource
    private OmcPlanService uacPlanService;

    @Resource
    private OmcPlanNewService planNewService;

    @Resource
    private OmcShiftsService omcShiftsService;

    /**
     * 排班方案-添加
     *
     * @param: [uacPlanDto, br]
     * @return: com.csun.cmny.util.wrapper.Wrapper
     */
    @ValidateAnnotation
    @LogAnnotation(isSaveRequestData = true, isSaveResponseData = true)
    @PostMapping(value = "/add")
    public Wrapper addUacPlan(@Validated(OmcPlanAddValidator.class)
                                @RequestBody PlanDto planDto,
                                BindingResult br) {
        //校验plan下的shifts集合
        String valid = checkShiftsList(planDto);

        if(valid.equals("ok")){
            planDto.setGroupId(getLoginAuthDto().getGroupId());
            Integer result = savePlan(planDto);

            if (result < 1) {
                return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                        .getMessage("operation.failed", null));
            }
            //return WrapMapper.ok(result);
            return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource
                    .getMessage("operation.success", null),result);
        }else{
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                    .getMessage(valid, null));
        }
    }

    /**
     * 排班方案-修改
     * @param: [uacPlanDto]
     * @return: com.csun.cmny.util.wrapper.Wrapper
     */
    @ValidateAnnotation
    @LogAnnotation(isSaveRequestData = true, isSaveResponseData = true)
    @PostMapping(value = "/edit")
    public Wrapper editUacPlan(@Validated(OmcPlanEditValidator.class)
                                @RequestBody PlanDto planDto,
                               BindingResult br
                               ){
        //获取交班项集合
        List<OmcShifts> omcShiftsList = planDto.getShiftsList();

        //校验交班项
        if(!CollectionUtils.isEmpty(omcShiftsList)){
            for(OmcShifts item : omcShiftsList){
                if(item.getId() == null || item.getId() == 0){
                    return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                            .getMessage("shifts.id.null", null));
                }
                String pattern = "([0-1]?[0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])-([0-1]?[0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])";
                if (!StringUtils.isBlank(item.getTime()) && !Pattern.matches(pattern, item.getTime())) {
                    return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                            .getMessage("shifts.time.error", null));
                }
            }
        }
        //放入机构id
        planDto.setGroupId(getLoginAuthDto().getGroupId());
        Integer result = savePlan(planDto);

        if (result < 1) {
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                    .getMessage("operation.failed", null));
        }
        //return WrapMapper.ok(result);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource
                .getMessage("operation.success", null),result);
    }

    /**
     * 排班方案-删除
     * @param: [planId]
     * @return: com.csun.cmny.util.wrapper.Wrapper
     */
    @ValidateAnnotation
    @LogAnnotation(isSaveRequestData = true, isSaveResponseData = true)
    @PostMapping(value = "/delete/{planId}")
    public Wrapper deleteUacPlan(@PathVariable Long planId){

        // 校验Id是否为空
        Preconditions.checkArgument(planId != null, cmnyMessageSource
                .getMessage("plan.id.null", null));
        Integer result = uacPlanService.deleteById(planId);

        if (result < 1) {
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                    .getMessage("operation.failed", null));
        }
        //return WrapMapper.ok(result);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource
                .getMessage("operation.success", null),result);
    }

    /**
     * 交班项-删除
     * @param: [planId]
     * @return: com.csun.cmny.util.wrapper.Wrapper
     */
    @ValidateAnnotation
    @LogAnnotation(isSaveRequestData = true, isSaveResponseData = true)
    @PostMapping(value = "/deleteShiftById/{shiftId}")
    public Wrapper deleteShiftById(@PathVariable Long shiftId){

        // 校验Id是否为空
        Preconditions.checkArgument(shiftId != null, cmnyMessageSource
                .getMessage("plan.id.null", null));
        Integer result = omcShiftsService.deleteById(shiftId);

        if (result < 1) {
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                    .getMessage("operation.failed", null));
        }
        //return WrapMapper.ok(result);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource
                .getMessage("operation.success", null),result);
    }

    /*
    * 排班方案-查询
    * */
    @ValidateAnnotation
    @LogAnnotation(isSaveRequestData = true, isSaveResponseData = true)
    @PostMapping(value = "/queryListAll")
    public Wrapper queryListAll(@RequestBody PlanQueryDto planQueryDto){

        planQueryDto.setGroupId(getLoginAuthDto().getGroupId());

        List<OmcPlan> omcPlans = uacPlanService.queryListAll(planQueryDto);

        //return WrapMapper.ok(omcPlans);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource
                .getMessage("operation.success", null),omcPlans);
    }

    /**
     * 保存排班方案
     * @param: [uacPlanDto]
     * @return: java.lang.Integer
     */
    private Integer savePlan(PlanDto planDto){
        OmcPlan omcPlan = new OmcPlan();
        BeanUtils.copyProperties(planDto, omcPlan);
        return uacPlanService.savePlan(omcPlan,getLoginAuthDto());
    }

    public String checkShiftsList(PlanDto planDto){

        if(planDto.getShiftsList().size() >= 0){
            List<OmcShifts> shiftsList = planDto.getShiftsList();
            if(!CollectionUtils.isEmpty(shiftsList)){
                for(int i=0;i<shiftsList.size();i++){
                    String name = shiftsList.get(i).getName();
                    String time = shiftsList.get(i).getTime();
                    Integer shifts = shiftsList.get(i).getShifts();
                    if(StringUtils.isBlank(name) || name.length() > 5){
                        return "shifts.name.error";
                    }
                    String pattern = "([0-1]?[0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])-([0-1]?[0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])";
                    if (StringUtils.isBlank(time) || !Pattern.matches(pattern, time)) {
                        return "shifts.time.error";
                    }
                    if(shifts == null || shifts < 0 || shifts > 1){
                        return "shifts.shifts.null";
                    }
                }
            }
        }
        return "ok";
    }

    /**
     * 新增排班方案
      * @param planNew
     * @return Wrapper
     * @author HD
     * @date 2021/11/5 17:52
     */
    @PostMapping("/insertNewPlan")
    public Wrapper insertNewPlan(@RequestBody OmcPlanNew planNew){
        OmcPlanNew omcPlanNew = new OmcPlanNew();
        omcPlanNew.setPlanName(planNew.getPlanName());
        omcPlanNew.setGroupId(getLoginAuthDto().getGroupId());
        List<OmcPlanNew> query = planNewService.query(omcPlanNew);
        if(query.size()>0){
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                    .getMessage("10070004", null));
        }
        planNew.setGroupId(getLoginAuthDto().getGroupId());
        planNew.setUpdateInfo(getLoginAuthDto());
        Integer result = planNewService.save(planNew);
        if (result < 1) {
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                    .getMessage("operation.failed", null));
        }
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource
                .getMessage("operation.success", null),result);
    }
    /**
     * 删除排班方案
      * @param planNew
     * @return Wrapper
     * @author HD
     * @date 2021/11/8 10:02
     */
    @PostMapping("/deleteNewPlan")
    public Wrapper deleteNewPlan(@RequestBody OmcPlanNew planNew){
        Integer result = planNewService.deleteByKey(planNew.getId());
        if (result < 1) {
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                    .getMessage("operation.failed", null));
        }
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource
                .getMessage("operation.success", null),result);
    }

    /**
     * 修改排班方案
      * @param planNew
     * @return Wrapper
     * @author HD
     * @date 2021/11/8 10:23
     */
    @PostMapping("/updateNewPlan")
    public Wrapper updateNewPlan(@RequestBody OmcPlanNew planNew){
        OmcPlanNew omcPlanNew = new OmcPlanNew();
        omcPlanNew.setPlanName(planNew.getPlanName());
        omcPlanNew.setGroupId(getLoginAuthDto().getGroupId());
        List<OmcPlanNew> query = planNewService.query(omcPlanNew);
        if(query.size()>0 && !query.get(0).getId().equals(planNew.getId())){
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                    .getMessage("10070004", null));
        }
        planNew.setGroupId(getLoginAuthDto().getGroupId());
        planNew.setUpdateInfo(getLoginAuthDto());
        Integer result = planNewService.update(planNew);
        if (result < 1) {
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                    .getMessage("operation.failed", null));
        }
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource
                .getMessage("operation.success", null),result);
    }

    /**
     * 查询排班方案
     * @param planNew
     * @return Wrapper
     * @author HD
     * @date 2021/11/8 10:23
     */
    @PostMapping("/queryPlanNew")
    public Wrapper queryPlanNew(@RequestBody OmcPlanNew planNew){
        List<OmcPlanNew> planNews = planNewService.query(planNew);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource
                .getMessage("operation.success", null),new PageInfo<>(planNews));
    }

}
